package cn.piggy.service;

import cn.piggy.model.translation.Query;
import cn.piggy.model.translation.TranRequestBody;
import cn.piggy.component.PiggyParam;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;

@Service
public class TranslationExecutorService extends BaseExecutorService {

    private final PiggyParam aiParam;
    @Autowired
    public TranslationExecutorService(OkHttpClient okHttpClient, PiggyParam aiParam) {
        super(okHttpClient);
        this.aiParam = aiParam;
    }

    public String syncExecuteTranCreate(TranRequestBody tranRequestBody) throws IOException {
        return executeHttpRequest(aiParam.getCreateHost(), tranRequestBody);
    }

    public String syncExecuteTranQuery(Query query) throws IOException {
        return executeHttpRequest(aiParam.getQueryHost(), query);
    }

    @Override
    public String queryToken() throws IOException {
        String clientId = aiParam.getApiKey();
        String clientSecret = aiParam.getSecretKey();
        String authHost = aiParam.getAuthHost();
        FormBody formBody = new FormBody.Builder()
                .add("grant_type","client_credentials")
                .add("client_id",clientId)
                .add("client_secret",clientSecret).build();
        Request request = new Request.Builder().url(authHost)
                .addHeader("Content-Type", "x-www-form-urlencoded").post(formBody).build();
        return requestToken(request);
    }

}
